<template>
	<div class="container">
		<div>
			<el-button type="primary" icon="el-icon-plus" @click="editVisible = true" v-permission
				class="toolBarButton">
				新增
			</el-button>
			<v-nodeNetworkToolBar :fullPath="postData.opera" :tableColumns="tableColumns" @changeLie="getChangeLie"
				@getSearchIPArr="getToolBarSearchIPArr" @getSearchIP="getToolBarSearchIP"
				@selectIsEnabled="getToolBarSelectIsEnabled" @selectOSType="getToolBarSelectOSType">
			</v-nodeNetworkToolBar>
		</div>
		<el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
			class="tableData" :data="tableDataFn" highlight-current-row @current-change="handleCurrentChange" border
			stripe style="width: 100%">
			<el-table-column type="index" :index="1" width="50" label="序号">
			</el-table-column>

			<template v-for="item in tableColumns">
				<el-table-column :prop="item.prop" :label="item.label" :sortable="item.sortable" :width="item.width"
					align="center" v-if="item.isShow" :key="item.prop">
					<template v-slot="scope">
						<template v-if="item.format == 'ISENABLED'">
							<div>
								<template v-if="scope.row[item.prop] == 'Y'">
									<el-tag type="success">监控中</el-tag>
								</template>
								<template v-else-if="scope.row[item.prop] == 'N'">
									<el-tag type="danger">待开启</el-tag>
								</template>
								<template v-else>
									<el-tooltip class="item" effect="dark" :content="scope.row[item.prop]"
										placement="right">
										<el-tag type="danger" effect="dark">异常值</el-tag>
									</el-tooltip>
								</template>
							</div>
						</template>
						<template v-else-if="item.format == 'user'">
							<div v-if="scope.row[item.prop] != 'F'">
								{{ scope.row[item.prop] }}
							</div>
							<div v-else style="text-align: center">
								<el-tag type="info" size="mini" effect="plain" style="width: 100%">
									&nbsp;空&nbsp;
								</el-tag>
							</div>
						</template>
						<template v-else-if="item.format == 'password'">
							<div v-if="scope.row[item.prop] != 'F'">
								<template v-if="scope.row['showPswd']">
									{{ scope.row[item.prop] }}
								</template>
								<template v-else>
									******
								</template>
								<i class="el-icon-view pswdBtn" @click="showPswdFn(scope.$index, scope.row)"></i>
							</div>
							<div v-else style="text-align: center">
								<el-tag type="info" size="mini" effect="plain" style="width: 100%">
									&nbsp;空&nbsp;
								</el-tag>
							</div>
						</template>
						<template v-else-if="item.format == 'handleRow'">
							<div>
								<el-button type="warning" @click="editNode(scope.row)" v-permission>编辑</el-button>
								<template v-if="scope.row['ISENABLED'] == 'Y'">
									<el-button type="danger" @click="editNodeMonitor(scope.row, 'N')" v-permission
										:disabled="scope.row.editNodeMonitorBtnDisabled">
										关闭监控
									</el-button>
								</template>
								<template v-else>
									<el-button type="success" @click="editNodeMonitor(scope.row, 'Y')" v-permission
										:disabled="scope.row.editNodeMonitorBtnDisabled">
										开启监控
									</el-button>
								</template>
							</div>
						</template>
						<template v-else-if="item.format == 'alertLevelConfig'">
							<div>
								{{ alertLevelConfigOptionText(scope.row[item.prop]) }}
							</div>
						</template>
						<template v-else>
							<div>
								{{ scope.row[item.prop] }}
							</div>
						</template>
					</template>
				</el-table-column>
			</template>
		</el-table>
		<v-pagination :dataTotal="dataTotal" :curPage="postData.curPage" :pageSize="postData.pageSize"
			@getCurPage="getPaginationCurPage" @getPageSize="getPaginationPageSize">
		</v-pagination>

		<!-- 新建、编辑对话框 -->
		<el-dialog :visible.sync="editVisible" width="24%" @close="resetForm('nodeForm')">
			<el-form :model="nodeForm" :rules="nodeFormRules" ref="nodeForm" label-width="120px">
				<el-form-item label="IP" prop="IP">
					<el-input v-model="nodeForm.IP"></el-input>
				</el-form-item>
				<el-form-item label="业务系统" prop="BID">
					<el-select v-model="nodeForm.BID" filterable>
						<el-option v-for="item in servicesNameOption" :key="item.BID" :label="item.NAME"
							:value="item.BID">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属监控组" prop="ALERT_LEVELCONFIG">
					<el-select v-model="nodeForm.ALERT_LEVELCONFIG" filterable>
						<el-option v-for="item in alertLevelConfigOptionFn" :key="item.ID" :label="item.TITLE"
							:value="item.ID">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="操作系统">
					<el-radio-group v-model="nodeForm.OS_TYPE" @change="changeOSType">
						<!-- <el-radio-button key="Linux" label="Linux"></el-radio-button>
                        <el-radio-button key="Windows" label="Windows"></el-radio-button> -->
						<!-- <el-radio-button key="Aix" label="Aix"></el-radio-button> -->
						<el-radio-button key="Network" label="Network"></el-radio-button>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="连接方式" prop="CONN_TYPE">
					<!-- <el-input v-model="nodeForm.CONN_TYPE"></el-input> -->
					<el-select v-model="nodeForm.CONN_TYPE" @change="changeConnType">
						<el-option v-for="item in connTypeOptionFn" :key="item.value" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="端口" prop="PORT">
					<el-input v-model="nodeForm.PORT" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入数字">
					</el-input>
				</el-form-item>
				<el-form-item label="标签" prop="LABLE">
					<el-input v-model="nodeForm.LABLE" placeholder="请输入标签">
					</el-input>
				</el-form-item>
				<el-form-item label="上一级标签" prop="PARENTLABLE">
					<!-- <el-input
            v-model="nodeForm.PARENTLABLE"
            placeholder="请输入上一级标签"
          >
          </el-input> -->
					<el-select @change="PARENTLABLEChange" v-model="nodeForm.PARENTLABLE" placeholder="请选择上一级"
						:clearable="true">
						<el-option v-for="item in LabelOptions" :key="item.value" :label="item.label"
							:value="item.value">
							<span style="float: left">{{ item.label }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{
                item.IP
              }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上一级网口" prop="PARENTLABLEPORT">
					<el-select v-model="nodeForm.PARENTLABLEPORT" placeholder="请选择上一级网口" :clearable="true">
						<el-option v-for="item in switchPortLabelOptions" :key="item.value" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="上一级端口" prop="PARENTLABLEPORT">
          <el-input
            v-model="nodeForm.PARENTLABLEPORT"
            onkeyup="value=value.replace(/[^\d]/g,'')"
            placeholder="请输入数字"
          >
          </el-input>
        </el-form-item> -->

				<el-form-item label="启用">
					<el-radio-group v-model="nodeForm.ISENABLED"
						:fill="nodeForm.ISENABLED == 'Y' ? '#67C23A' : '#F56C6C'">
						<el-radio-button key="Y" label="Y">开启</el-radio-button>
						<el-radio-button key="N" label="N">关闭</el-radio-button>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="用户名" prop="HOST_MONITOR_S" v-if="nodeForm.CONN_TYPE != 'snmp'">
					<el-input v-model="nodeForm.HOST_MONITOR_S"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="HOST_MONPWD_S" v-if="nodeForm.CONN_TYPE != 'snmp'">
					<el-input v-model="nodeForm.HOST_MONPWD_S" show-password></el-input>
				</el-form-item>
			</el-form>

			<span slot="footer">
				<el-button @click="editVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitData('nodeForm')" :disabled="submitBtnDisabled">
					确 定
				</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		submitAdmin,
		getManagementLabelOptions,
		getPARENTLABLEPORT,
	} from "@/api/index.js";
	import vPagination from "common/Pagination.vue";
	import vNodeNetworkToolBar from "./NodeNetworkToolBar.vue";
	import tableColumns from "./NodeNetworkColumns.js";
	export default {
		components: {
			vPagination,
			vNodeNetworkToolBar,
		},
		data() {
			let validateLable = (rule, value, callback) => {
				let pattern =
					/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
				if (pattern.test(value)) {
					callback(new Error("请不要以ipv4地址作为标签"));
				} else {
					callback();
				}
			};
			return {
				postData: {
					opera: "GetHostMonitor",
					curPage: 1,
					pageSize: 20,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "fuzzyquery",
					filters: {
						OS_TYPE: "Network"
					},
				},
				tableData: [],
				dataTotal: 0,
				tableColumns: tableColumns,
				SearchIPArr: [],
				searchJson: {},
				SearchIP: "",
				editVisible: false,
				submitBtnDisabled: false,
				editNodeMonitorBtnDisabled: false,
				nodeForm: {
					// HID: '',    编辑用到
					IP: "",
					BID: "0",
					ALERT_LEVELCONFIG: "0",
					OS_TYPE: "Network",
					CONN_TYPE: "ssh",
					PORT: 22,
					ISENABLED: "Y",
					HOST_MONITOR_S: "",
					HOST_MONPWD_S: "",
					LABLE: "",
					PARENTLABLE: "",
					PARENTLABLEPORT: "",
				},
				nodeFormRules: {
					IP: [{
							required: true,
							message: "请输入IP",
							trigger: "blur"
						},
						{
							pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,
							message: "请输入正确的IP",
						},
					],
					CONN_TYPE: [{
						required: true,
						message: "请输入连接方式",
						trigger: "blur"
					}, ],
					PORT: [{
						required: true,
						message: "请输入端口",
						trigger: "blur"
					}],
					HOST_MONITOR_S: [{
						required: true,
						message: "请输入用户名",
						trigger: "blur"
					}, ],
					HOST_MONPWD_S: [{
						required: true,
						message: "请输入密码",
						trigger: "blur"
					}, ],
					LABLE: [{
							required: true,
							message: "请输入标签",
							trigger: "blur"
						},
						{
							validator: validateLable,
							trigger: "blur"
						},
					],
					PARENTLABLEPORT: [
						// { required: true, message: "请输入标签", trigger: "blur" },
						{
							pattern: /^(?:[1-9]|([1-3][0-9])?|4[0-8])$/,
							message: "请输入正确的端口",
						},
					],
				},
				createOpera: "CreateHostMonitor",
				modifyOpera: "ModifyHostMonitor",
				loading: true,
				alertLevelConfigOption: [],
				servicesNameOption: [],
				LabelOptions: [],
				switchPortArr: Array.from(Array(48), (v, k) => k + 1),
				switchPortLabelOptions: [],
			};
		},
		created() {
			this.getTableData();
			this.getAlertGroupIndex();
			this.getServicesNameOption();
			this.getLabelOptions();
		},
		computed: {
			tableDataFn() {
				return this.tableData.filter((item) => {
					item["showPswd"] = false;
					item["editNodeMonitorBtnDisabled"] = false;
					// item['OS_TYPE']=
					// return item["OS_TYPE"] == "Network";
					return item;
				});
			},
			connTypeOptionFn() {
				if (this.nodeForm.OS_TYPE != "Windows") {
					return [{
							value: "ssh",
							label: "ssh"
						},
						{
							value: "snmp",
							label: "snmp"
						},
					];
				} else {
					return [{
						value: "snmp",
						label: "snmp"
					}];
				}
			},
			alertLevelConfigOptionFn() {
				return this.alertLevelConfigOption.filter((item) => {
					if (item.GROUP_TYPE == "ALL" || item.GROUP_TYPE == "Host") {
						return item;
					}
				});
			},
		},
		methods: {
			async getTableData() {
				this.loading = true;
				this.tableData = [];
				// await getUserData("userBase", "infoBase", 0).then((res) => {
				//   this.userAuthority = res.userAuthority;
				// });
				submitAdmin({
					postData: JSON.stringify(this.postData),
				}).then((res) => {
					console.log(res)
					// this.dataTotal = res.dataTotal;
					// let Total = 0;
					// res.data.forEach((item) => {
					//   if (item["OS_TYPE"] == "Network") {
					//     Total += 1;
					//     this.tableData.push(item)
					//   }
					// });
					this.dataTotal = res.dataTotal;
					this.tableData = res.data;

					this.loading = false;
				});
			},
			getAlertGroupIndex() {
				let _postData = {
					opera: "GetAlertGroupIndex",
					curPage: 1,
					pageSize: 10000,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "exactquery", // 精确查询
					filters: {},
				};

				submitAdmin({
					postData: JSON.stringify(_postData),
				}).then((res) => {
					this.alertLevelConfigOption = res.data;
				});
			},
			getServicesNameOption() {
				let _postData = {
					opera: "GetServicesName",
					curPage: 1,
					pageSize: 10000,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "exactquery", // 精确查询
					filters: {},
				};

				submitAdmin({
					postData: JSON.stringify(_postData),
				}).then((res) => {
					this.servicesNameOption = res.data;
				});
			},
			alertLevelConfigOptionText(id) {
				let _text = "";
				this.alertLevelConfigOption.forEach((element) => {
					if (element.ID == id) {
						_text = element.TITLE;
					}
				});

				return _text;
			},
			PARENTLABLEChange(name) {
				getPARENTLABLEPORT({
					name
				}).then((_) => {
					if (_ && _.length > 0) {
						_.forEach((item) => {
							const index = this.switchPortArr.findIndex((i) => i == item);
							if (index != -1) {
								this.switchPortArr.splice(index, 1);
							}
						});
						this.switchPortLabelOptions = this.getSwitchPortLabelOptions(
							this.switchPortArr
						);
					} else {
						this.switchPortLabelOptions = [];
						// this.$message.error(500);
					}
				});
			},
			getSwitchPortLabelOptions(arr) {
				return arr.map((item) => {
					return {
						label: item,
						value: item,
					};
				});
			},
			getPaginationCurPage(val) {
				this.postData.curPage = val;

				this.getTableData();
			},
			getPaginationPageSize(val) {
				// 分页大小改变之后，重置当前页码为 1
				this.postData.curPage = 1;
				this.postData.pageSize = val;

				this.getTableData();
			},
			getToolBarSearchIPArr(arr) {
				// 获取搜索IP关键字
				this.SearchIPArr = arr;

				this.postData.curPage = 1;
				if (this.SearchIPArr.length > 0) {
					this.postData.filters = {
						ip: this.SearchIPArr,
					};
				} else {
					this.postData.filters = {};
				}

				this.getTableData();
			},
			getToolBarSearchIP(str) {
				// 获取搜索IP关键字
				this.SearchIP = str;
				this.postData.curPage = 1;
				this.postData.filters = {
					ip: this.SearchIP,
					OS_TYPE: "Network",
				};
				this.getTableData();
			},
			getToolBarSelectIsEnabled(val) {
				this.postData.filters["ISENABLED"] = val;
				this.getTableData();
			},
			getToolBarSelectOSType(val) {
				this.postData.filters["OS_TYPE"] = val;
				this.getTableData();
			},
			getChangeLie(val) {
				// 遍历表格列
				this.tableColumns.map((item, index) => {
					// 列的显示隐藏状态改变
					item.isShow = val.includes(item.label);
				});
			},
			handleCurrentChange(currentRow, oldCurrentRow) {
				if (currentRow != null) {
					currentRow["isEdit"] = true;
				}
				if (oldCurrentRow != null) {
					oldCurrentRow["isEdit"] = false;
				}
			},
			resetForm(formName) {
				let _data = new Object();
				Object.assign(_data, this.$options.data()[formName]);
				this.$data[formName] = _data;

				// 移除表单校验结果
				this.$refs[formName] && this.$refs[formName].clearValidate();
			},
			submitData(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// 禁用按钮，避免重复提交
						this.submitBtnDisabled = true;

						// 处理需要提交数据
						let _postData = {
							opera: "",
							data: [this.nodeForm],
						};
						if (this.nodeForm.hasOwnProperty("HID")) {
							_postData.opera = this.modifyOpera;
						} else {
							_postData.opera = this.createOpera;
						}

						// 提交数据
						submitAdmin({
							postData: JSON.stringify(_postData),
						}).then((res) => {
							if (res == "创建成功" || res == "修改成功") {
								this.$message.success({
									message: "操作成功",
									duration: 1000,
								});
								this.editVisible = false;
								this.getTableData();
							} else {
								this.$message.error({
									message: "操作失败",
									duration: 3000,
								});
							}
							// 启用按钮
							this.submitBtnDisabled = false;
						});
					} else {
						return false;
					}
				});
			},
			editNode(rowData) {
				for (const key in this.nodeForm) {
					if (rowData.hasOwnProperty(key)) {
						this.nodeForm[key] = rowData[key];
					}
				}
				this.PARENTLABLEChange(rowData.PARENTLABLE);
				this.nodeForm.HID = rowData.HID;
				this.editVisible = true;
			},
			editNodeMonitor(rowData, flag) {
				// 禁用按钮
				rowData.editNodeMonitorBtnDisabled = true;

				// 数据处理
				let _postData = {
					opera: this.modifyOpera,
					data: [this.nodeForm],
				};
				for (const key in _postData.data[0]) {
					if (rowData.hasOwnProperty(key)) {
						_postData.data[0][key] = rowData[key];
					}
				}
				_postData.data[0].HID = rowData.HID;
				_postData.data[0].ISENABLED = flag;

				// 提交数据
				submitAdmin({
					postData: JSON.stringify(_postData),
				}).then((res) => {
					let _this = rowData;

					if (res == "修改成功") {
						this.$message.success({
							message: "操作成功",
							duration: 1000,
							onClose: function() {
								_this.editNodeMonitorBtnDisabled = false;
							},
						});
						this.getTableData();
					} else {
						this.$message.error({
							message: "操作失败",
							duration: 1000,
							onClose: function() {
								_this.editNodeMonitorBtnDisabled = false;
							},
						});
					}
				});

				// 清空绑定的数据
				this.resetForm("nodeForm");
			},
			searchData() {
				this.postData.filters["IP"] = this.searchIP;
				this.getTableData();
			},
			showPswdFn(index, row) {
				row["showPswd"] = !row["showPswd"];
				// 更新数据
				this.$set(this.tableDataFn, index, row);
			},
			changeOSType(val) {
				switch (val) {
					case "Linux":
						this.nodeForm.CONN_TYPE = "ssh";
						this.nodeForm.PORT = 22;
						break;
					case "Windows":
						this.nodeForm.CONN_TYPE = "snmp";
						this.nodeForm.PORT = 161;
						break;
					case "Aix":
						this.nodeForm.CONN_TYPE = "ssh";
						this.nodeForm.PORT = 22;
						break;
					case "Network":
						this.nodeForm.CONN_TYPE = "snmp";
						this.nodeForm.PORT = 161;
						break;

					default:
						break;
				}
			},
			changeConnType(val) {
				switch (val) {
					case "ssh":
						this.nodeForm.PORT = 22;
						break;
					case "snmp":
						this.nodeForm.PORT = 161;
						break;

					default:
						break;
				}
			},
			getLabelOptions() {
				getManagementLabelOptions().then((_) => {
					if (_) {
						this.LabelOptions = Object.entries(_).map((item) => {
							return {
								label: item[1],
								value: item[1],
								IP: item[0],
							};
						});
					}
				});
			},
		},
		watch: {},
	};
</script>

<style scoped>
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

	.toolBarButton {
		float: left;
		padding-bottom: 10px;
		margin-right: 20px;
	}

	.pswdBtn {
		float: right;
		line-height: 23px;
		color: #67c23a;
		font-size: 18px;
	}

	.pswdBtn:hover {
		cursor: pointer;
	}
</style>
